package cn.tedu;

import java.sql.*;
import java.util.Scanner;

public class Demo07 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名和密码");
        String username = sc.nextLine();
        System.out.println("请输入密码");
        String password = sc.nextLine();
        try (
                Connection conn = DBUtils.getConn()) {
//            String sql = "select count(*) from user where username='"+username+"'" +
//                    "and password='"+password+"'";
//            Statement s = conn.createStatement();
//            ResultSet rs = s.executeQuery(sql);
            //使用PreparedStatement避免出现SQL注入漏洞
            String sql = "select count(*) from user " +
                    "where username=? and password=?";
            /*
            * 预编译的SQL执行对象,将编译SQL语句的时间点从执行时提前到创建时
            * 创建时对SQL语句进行编译将SQL中的逻辑锁死,用户输入的内容只能以
            * 值得形式添加到原SQL语句中,这样原有SQL语句的逻辑部分不会被
            * 用户输入的内容所改变,从而解决了SQL注入的问题*/
            PreparedStatement ps = conn.prepareStatement(sql);
            //替换?的值
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            rs.next();
            int count = rs.getInt(1);
            if (count > 0) {
                System.out.println("登录成功");
            } else {
                System.out.println("用户名或密码错误");
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
